package com.example.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.common.Result;
import com.example.common.constant.ResultCode;
import com.example.common.exception.ServiceException;
import com.example.domain.dto.UserDTO;
import com.example.domain.dto.UserRoleDTO;
import com.example.domain.entity.Menu;
import com.example.domain.entity.Role;
import com.example.domain.entity.User;
import com.example.domain.query.UserQuery;
import com.example.service.MenuService;
import com.example.service.RoleService;
import com.example.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Tag(name = "用户管理")
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;
    private final MenuService menuService;
    private final RoleService roleService;

    @Operation(summary = "获取用户列表")
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:user:query')")
    public Result<IPage<User>> list(UserQuery query) {
        try {
            log.debug("Query user list with params: {}", query);
            IPage<User> page = userService.getUserPage(query);
            log.debug("Found {} users", page.getTotal());
            return Result.success(page);
        } catch (Exception e) {
            log.error("Failed to query user list", e);
            return Result.error("查询用户列表失败");
        }
    }

    @Operation(summary = "获取用户详情")
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:user:query')")
    public Result<User> getInfo(@PathVariable Long id) {
        return Result.success(userService.getUserById(id));
    }

    @Operation(summary = "新增用户")
    @PostMapping
    @PreAuthorize("hasAuthority('sys:user:add')")
    public com.example.common.Result<?> add(@RequestBody @Valid UserDTO userDTO) {
        userService.addUser(userDTO);
        return Result.success();
    }

    @Operation(summary = "修改用户")
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:user:update')")
    public Result<?> update(@PathVariable Long id, @RequestBody @Valid UserDTO userDTO) {
        userDTO.setId(id);
        userService.updateUser(userDTO);
        return Result.success();
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result<?> delete(@PathVariable Long id) {
        userService.deleteUser(id);
        return Result.success();
    }

    @Operation(summary = "批量删除用户")
    @DeleteMapping("/batch")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result<?> batchDelete(@RequestBody List<Long> ids) {
        userService.batchDeleteUser(ids);
        return Result.success();
    }

    @Operation(summary = "获取当前用户信息")
    @GetMapping("/info")
    public Result<Map<String, Object>> getUserInfo() {
        // 获取当前用户
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userService.getUserByUsername(username);
        if (user == null) {
            throw new ServiceException(ResultCode.USER_NOT_FOUND);
        }

        // 获取用户角色
        List<Long> roleIds = userService.getUserRoleIds(user.getId());
        List<Role> roles = roleService.listByIds(roleIds);
        // 设置到用户对象中
        user.setRoleIds(roleIds);
        user.setRoles(roles);
        List<String> roleCodes = roles.stream().map(Role::getCode).collect(Collectors.toList());

        // 获取用户菜单
        List<Menu> menus = menuService.getUserMenus();
        
        // 获取用户权限
        List<String> permissions = menuService.getUserPermissions();

        // 构建返回数据
        Map<String, Object> result = new HashMap<>();
        result.put("user", user);
        result.put("roles", roleCodes);  // 确保返回角色编码列表
        result.put("permissions", permissions);
        result.put("menus", menus);

        return Result.success(result);
    }

    @Operation(summary = "修改密码")
    @PostMapping("/password")
    public Result<?> updatePassword(@RequestParam String oldPassword, @RequestParam String newPassword) {
        userService.updatePassword(oldPassword, newPassword);
        return Result.success();
    }

    @Operation(summary = "获取用户角色")
    @GetMapping("/{userId}/roles")
    @PreAuthorize("hasAuthority('sys:user:query')")
    public Result<List<Long>> getUserRoles(@PathVariable Long userId) {
        return Result.success(userService.getUserRoleIds(userId));
    }

    @Operation(summary = "分配用户角色")
    @PostMapping("/assign-roles")
    @PreAuthorize("hasAuthority('sys:user:update')")
    public Result<?> assignRoles(@RequestBody @Valid UserRoleDTO userRoleDTO) {
        userService.assignRoles(userRoleDTO.getUserId(), userRoleDTO.getRoleIds());
        return Result.success();
    }
} 